package com.dianrui.qiyouriding.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.bean.DeviceItem;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DeviceAdapter extends BaseAdapter {
    private ArrayList<DeviceItem> mDevices;
    private LayoutInflater mInflator;
    private DeviceClickListener deviceClickListener;

    public DeviceAdapter(ArrayList<DeviceItem> mDevices) {
        this.mDevices = mDevices;
    }

    public void addDevice(DeviceItem device) {
        int index = mDevices.indexOf(device);
        if (index < 0) {
            mDevices.add(device);
        } else {
           DeviceItem item = mDevices.get(index);

        }
    }

    public DeviceItem getDevice(int position) {
        return mDevices.get(position);
    }

    public void clear() {
        mDevices.clear();
    }

    @Override
    public int getCount() {
        return mDevices != null ? mDevices.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return mDevices.get(position);
    }

    public interface DeviceClickListener {
        void onDeivceClick(String deviceName);
    }

    public void setDeviceClickListener(DeviceClickListener deivceClickListener) {
        this.deviceClickListener = deivceClickListener;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView != null) {
            viewHolder = (ViewHolder) convertView.getTag();
        } else {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.findcar_item, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }
        if (mDevices.size() > 0) {
            final DeviceItem deviceItem = mDevices.get(position);
            viewHolder.deviceName.setText(deviceItem.devName);
            viewHolder.uses_car.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    deviceClickListener.onDeivceClick(deviceItem.devName);
                }
            });

        }

        return convertView;
    }

    class ViewHolder {
        @BindView(R.id.device_name)
        TextView deviceName;
        @BindView(R.id.use)
        Button uses_car;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);

        }
    }

}

